package com.etlmaster.executor.utils;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.etlmaster.core.BeanFactory;
import com.etlmaster.core.DataSourceDefine;
import com.etlmaster.core.DataSourceHolder;
import com.etlmaster.executor.utils.DataCollectionUtils;
import com.etlmaster.executor.utils.DpExecutorUtils;
import com.etlmaster.executor.utils.LogWriter;
import com.etlmaster.executor.utils.Regex;
import com.etlmaster.executor.utils.XmlParser;
import com.etlmaster.jdbc.JdbcTemplate;


/**
 * 数据源加载类
 * 
 * @author Wugf
 * @date 2016-03-08
 */
public class LoadDataSourceInfo {
	private static void initDbSource(String command){
		List objList;
		String regex=DataCollectionUtils.getProperties("localMode");
		String proc_name;
		if(Regex.validation(command, regex)){
			proc_name=Regex.validation(command, regex, 1);
			objList=XmlParser.parseXMLUtils(proc_name,"db");
		}else{
			JdbcTemplate jdbcTemplate=new JdbcTemplate();
			Map<String,Object> map=DpExecutorUtils.parseArgs(command);
			proc_name=(String) map.get("f");
			if(map.containsKey("teamCode")){
				map.put("team_code", map.get("teamCode"));
			}else{
				map.put("team_code", DataCollectionUtils.getTeamCode(proc_name, jdbcTemplate));
			}
			
			String sql=DataCollectionUtils.getProperties("fetchDbInfo");
			sql=DpExecutorUtils.variableSubstitution(sql, map);
			objList=jdbcTemplate.queryForList(sql);
		}
		new TeamDatasourceHolder(objList);
	}
	private static void registDataBaseConn() {
		LogWriter.addLog("INFO", "初始化数据库连接信息");
		
		Map<String, DataSourceDefine> defs = TeamDatasourceHolder.getInstance()
				.getDsDefs();
		String dbName = "";
		String dbCNName = "";

		for (Iterator iterator = defs.entrySet().iterator(); iterator.hasNext();) {
			try {
				Map.Entry<String, DataSourceDefine> entry = (Map.Entry<String, DataSourceDefine>) iterator
						.next();
				DataSourceDefine def = entry.getValue();
				dbName = def.getId();
				dbCNName = def.getName();
				DataSourceHolder.getInstance().addDsDefs(dbName, def);
				BeanFactory.registerBeanDefinition(
						def.getId(),
						TeamDatasourceHolder.getInstance()
								.genDataSourceBeanDefinition(def.getUrl(),
										def.getDriverClassName(),
										def.getUsername(), def.getPassword()),
						def.getAlias());
				if(checkStringNotEmpty(def.getUrl())&&checkStringNotEmpty(def.getDriverClassName()))
					LogWriter.addLog("INFO", "数据源：[{}:{}]注入成功", def.getId(),
						def.getName());
				else{
					LogWriter.addLog("warn", "数据源：[{}:{}] 连接串/驱动类为空", def.getId(),
							def.getName());
				}
			} catch (Exception e) {
				LogWriter.addLog("ERROR", "数据源：[{}:{}]注入异常，请检查配置", dbName,
						dbCNName);
				// e.printStackTrace();
			}
		}

	}
	public static boolean checkStringNotEmpty(String str){
		if(str!=null&&str.length()>0){
			return true;
		}
		return false;
	}
	public static void loadDataInfo(String command){
		initDbSource(command);
		registDataBaseConn();
	}
}
